package saucaca.fragment;

import java.util.Calendar;

import lemon.kenhnhacvn.BaseActivity;
import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;

import org.json.JSONException;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import saucaca.CustomView.CircularImageView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AccountObject;
import saucaca.Object.HomeData;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

public class AccountUpdateInfoFragment extends Fragment {
	String TAG = AccountRegisterFragment.class.getSimpleName();

	private static final int SELECT_PICTURE = 1;
	String imagePath = "";
	private MainActivity mActivity = null;
	Resources resources;
	TextView txtAvatarPath;
	EditText edtFullname, edtPhone, edtBirthday, edtPassOld, edtPassNew, edtPassNew2;
	CircularImageView account_avatar, account_avatarChoose;
	String day, month, year;
	RadioGroup radioGroup;
	String strAvatar, userName, fullName, birthday, phone, sex;
	Bitmap bitmap;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// getActivity().getActionBar().hide();
		resources = getResources();
		View view = inflater.inflate(R.layout.account_updateinfo, container, false);
		findViewById(view);

		strAvatar = PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar);
		userName = PreferenceUtils.getString(mActivity, TagName.KeyPreference_user);
		fullName = PreferenceUtils.getString(mActivity, TagName.KeyPreference_fullname);
		birthday = PreferenceUtils.getString(mActivity, TagName.KeyPreference_birthday);
		phone = PreferenceUtils.getString(mActivity, TagName.KeyPreference_phone);
		sex = PreferenceUtils.getString(mActivity, TagName.KeyPreference_sex);
		if (strAvatar != null) {
			Bitmap bitmap = BaseEngine.BitmapFromBase64(strAvatar);
			account_avatar.setImageBitmap(bitmap);
		}
		if (fullName != null) {
			edtFullname.setText(fullName);
		}
		if (birthday != null) {
			edtBirthday.setText(birthday);
		}
		if (phone != null) {
			edtPhone.setText(phone);
		}
		if (sex != null) {
			String _sex = BaseEngine.convertStringLongtoInteger(sex);
			if (_sex.equals("1")) {
				radioGroup.check(R.id.personalprofile_Nam);
			} else if (_sex.equals("2")) {
				radioGroup.check(R.id.personalprofile_Nu);
			} else if (_sex.equals("0")) {
				radioGroup.check(R.id.personalprofile_Other);
			}
		}
		 new getinfoAsyns().execute("");
			mActivity.myActionBar.setMenu(R.string.account_info, false, true);
			return view;
		}
		@Override
		public void onHiddenChanged(boolean hidden) {
			super.onHiddenChanged(hidden);
			mActivity.myActionBar.setMenu(R.string.account_info, false, true);
		}

	public void findViewById(View view) {
		radioGroup = (RadioGroup) view.findViewById(R.id.acount_update_radiogroup);
		txtAvatarPath = (TextView) view.findViewById(R.id.account_avatarchoose_Text);
		edtFullname = (EditText) view.findViewById(R.id.account_edt_fullname);
		edtBirthday = (EditText) view.findViewById(R.id.account_edt_birthday);
		edtPhone = (EditText) view.findViewById(R.id.account_edt_phonenumber);
		edtPassOld = (EditText) view.findViewById(R.id.account_edt_passold);
		edtPassNew = (EditText) view.findViewById(R.id.account_edt_passnew);
		edtPassNew2 = (EditText) view.findViewById(R.id.account_edt_passrenew);
		account_avatar = (CircularImageView) view.findViewById(R.id.account_avatar);
		account_avatarChoose = (CircularImageView) view.findViewById(R.id.account_avatarchoose);
		account_avatar.setOnClickListener(clickListener);
		edtBirthday.setOnClickListener(clickListener);
		((Button) view.findViewById(R.id.account_buttonChooseAvatar)).setOnClickListener(clickListener);
		((LinearLayout) view.findViewById(R.id.account_button_updateinfo)).setOnClickListener(clickListener);
		((LinearLayout) view.findViewById(R.id.account_button_changepass)).setOnClickListener(clickListener);
		edtBirthday.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showDatedialog();
				}
			}
		});
	}

	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.account_avatar:
				chooseImage();
				break;
			case R.id.account_buttonChooseAvatar:
				chooseImage();
				break;	
			case R.id.account_button_updateinfo:
				if (bitmap != null)
					new updateAvatar().execute("");
				new updateinfoAsyns().execute("");
				break;
			case R.id.account_button_changepass:
				if (!edtPassOld.getText().toString().equals("") && !edtPassNew.getText().toString().equals("") && !edtPassNew2.getText().toString().equals("")) {
					if (edtPassNew.getText().toString().equals(edtPassNew2.getText().toString())) {
						new changePassAsyns().execute("");
					} else
						TagName.showToastShort(mActivity, "Nhập lại mật khẩu không đúng!");
				} else
					TagName.showToastShort(mActivity, "Bạn phải nhập đủ thông tin!");
				break;
			case R.id.account_edt_birthday:
				showDatedialog();
				break;
			default:
				break;
			}
		}
	};

	public void chooseImage() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == mActivity.RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				try {
					Uri selectedImageUri = data.getData();
					imagePath = selectedImageUri.getPath();
					TagName.showLogError("Updateinfo", imagePath);
					bitmap = BitmapFactory.decodeFile(imagePath);
					if (bitmap != null) {
						txtAvatarPath.setText(imagePath);
						account_avatarChoose.setImageBitmap(bitmap);
					}else{
						String http="http";
						String path=imagePath.substring(imagePath.lastIndexOf(http));
						TagName.showLogError("Updateinfo","path:"+ path);
						ImageLoader.getInstance().loadImage(path, new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view, loadedImage);
//								PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(mActivity, loadedImage));
								txtAvatarPath.setText(imagePath);
								bitmap = loadedImage;
								account_avatarChoose.setImageBitmap(bitmap);
							}
						});
					}
				} catch (Exception e) {
				}
			}
		}
	}

	public void showDatedialog() {
		final Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog dpd = new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				edtBirthday.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
			}
		}, year, month, day);
		dpd.show();
	}

	String checkSexchecked() {
		int intcheck = radioGroup.indexOfChild(radioGroup.findViewById(radioGroup.getCheckedRadioButtonId()));
		switch (intcheck) {
		case 1:
			return "2";
		case 2:
			return "0";
		default:
			return "1";
		}
	}

	class updateinfoAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String fullName = edtFullname.getText().toString();
			String sex = checkSexchecked();
			String birthDay = checkDate(edtBirthday.getText().toString());
			String phone = edtPhone.getText().toString();
			String str = WServiceLib.account_updateinfo(userName, fullName, sex, birthDay, phone);

			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
				// BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null) {
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
			}
		}
	}

	class updateAvatar extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.account_uploadAvatar(BaseEngine.BitmapTobase64(bitmap), userName, "0");
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null&& HomeData.headerObject.getCODE().equals("0")) {
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
			}
		}
	}

	class getinfoAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.account_info(userName);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if(result!=null){
				BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
					if(HomeData.headerObject != null&& HomeData.headerObject.getCODE().equals("0"))
						showInfoAccount(JsonReader.readUserInfo(result));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}

	void showInfoAccount(AccountObject accountObject){
		if(accountObject!=null){
		BaseActivity.imageLoader.displayImage(accountObject.getAVATAR(), account_avatar, BaseActivity.options);
		edtFullname.setText(accountObject.getFULL_NAME());
		edtBirthday.setText(accountObject.getBIRTH_DAY());
		edtPhone.setText(accountObject.getMOBILE());
		if (accountObject.getSEX() != null) {
			String _sex = BaseEngine.convertStringLongtoInteger(accountObject.getSEX());
			if (_sex.equals("1")) {
				radioGroup.check(R.id.personalprofile_Nam);
			} else if (_sex.equals("2")) {
				radioGroup.check(R.id.personalprofile_Nu);
			} else if (_sex.equals("0")) {
				radioGroup.check(R.id.personalprofile_Other);
			}
		}
	}}
	private static String checkDate(String date) {
		String[] dates = BaseEngine.stringtoArray(date, "/");
		String s = "";
		for (int i = 0; i < dates.length; i++) {
			switch (i) {
			case 0:
				if (dates[i].length() < 2) {
					s += "0" + dates[i];
				} else
					s += dates[i];
				break;
			case 1:
				if (dates[i].length() < 2) {
					s += "/0" + dates[i];
				} else
					s += "/" + dates[i];
				break;
			default:
				s += "/" + dates[i];
				break;
			}

		}
		return s;
	}

	class changePassAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String passOld = edtPassOld.getText().toString();
			String passNew = edtPassNew.getText().toString();
			String str = WServiceLib.account_changePass(userName, passOld, passNew);
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
				// BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null) {
				if (HomeData.headerObject.getCODE().equals("0")) {
					edtPassOld.setText("");
					edtPassNew.setText("");
					edtPassNew2.setText("");
				}
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
			}
		}

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}
}